<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DeepSeek Linux 命令优化器</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
        textarea { width: 100%; height: 100px; margin-bottom: 10px; }
        button { padding: 10px 15px; background: #007bff; color: white; border: none; cursor: pointer; margin-right: 10px; }
        button:hover { background: #0056b3; }
        #result { margin-top: 20px; padding: 15px; background: #f8f9fa; border: 1px solid #ddd; border-radius: 5px; }
        #feedback-section { margin-top: 20px; padding: 15px; background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 5px; }
        #feedback-input { width: 100%; height: 80px; margin-top: 10px; }
        #submit-feedback { background: #ffc107; color: #333; }
        #submit-feedback:hover { background: #e0a800; }
        #save-options { margin-top: 20px; }
        .success { color: #28a745; font-weight: bold; }
    </style>
</head>
<body>
<h1>文本转 Linux 命令（可优化）</h1>
<p>粘贴任意文本，AI 会生成命令，并根据你的反馈持续优化：</p>

<textarea id="inputText" placeholder="例如：查找当前目录下所有 .log 文件并删除"></textarea>
<button onclick="generateInitialCommand()">生成初始命令</button>

<div id="result">
    <h3>当前命令：</h3>
    <pre id="commandOutput">等待生成...</pre>
    <div id="optimization-history" style="margin-top: 10px; font-size: 0.9em; color: #666;"></div>
</div>

<div id="feedback-section">
    <h3>反馈优化</h3>
    <p>如果命令不准确，请输入改进建议（例如：“缺少权限参数”）：</p>
    <textarea id="feedback-input" placeholder="例如：生成的命令缺少 sudo..."></textarea>
    <button onclick="optimizeCommand()">优化命令</button>
    <div id="feedback-response" style="margin-top: 10px;"></div>
</div>

<div id="save-options" style="display: none;">
    <h3>保存结果</h3>
    <p class="success">命令已优化完成！请选择保存方式：</p>
    <button onclick="saveAsDocument()">保存为文本文件</button>
    <button onclick="saveToMySQL()">存入 MySQL 数据库</button>
</div>

<script>
    let sessionID = Date.now(); // 唯一会话 ID，用于跟踪优化过程
    let isOptimized = false;//经过优化的

    // 生成初始命令
    async function generateInitialCommand() {
        const inputText = document.getElementById("inputText").value;
        if (!inputText.trim()) {
            alert("请输入文本！");
            return;
        }

        const response = await fetch("/generate", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
                text: inputText,
                session_id: sessionID,
                is_initial: true
            })
        });

        const data = await response.json();
        document.getElementById("commandOutput").textContent = data.command;
        document.getElementById("optimization-history").innerHTML =
            `<strong>优化历史：</strong><br>- 初始命令: ${data.command}`;
        document.getElementById("feedback-section").style.display = "block";
        isOptimized = false;
    }

    // 优化命令
    async function optimizeCommand() {
        const feedback = document.getElementById("feedback-input").value;
        if (!feedback.trim()) {
            alert("请输入反馈内容！");
            return;
        }

        const response = await fetch("/optimize", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
                feedback: feedback,
                session_id: sessionID
            })
        });

        const data = await response.json();
        document.getElementById("commandOutput").textContent = data.command;

        // 更新优化历史
        const historyDiv = document.getElementById("optimization-history");
        const newHistory = historyDiv.innerHTML + `<br>- 反馈: "${feedback}" → 优化后: ${data.command}`;
        historyDiv.innerHTML = newHistory;

        // 清空反馈输入框
        document.getElementById("feedback-input").value = "";
        document.getElementById("feedback-response").textContent = "命令已优化！";

        // 检查是否满足终止条件（例如用户输入“可以了”）
        if (feedback.toLowerCase().includes("可以了") || feedback.toLowerCase().includes("确认")) {
            isOptimized = true;
            document.getElementById("save-options").style.display = "block";
            document.getElementById("feedback-section").style.display = "none";
        }
    }

    // 保存为文本文件
    async function saveAsDocument() {
        if (!isOptimized) {
            alert("请先优化命令！");
            return;
        }

        const command = document.getElementById("commandOutput").textContent;
        const blob = new Blob([command], { type: "text/plain" });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = `linux_command_${sessionID}.txt`;
        a.click();
        alert("文档已保存！");
    }

    // 存入 MySQL（模拟）
    async function saveToMySQL() {
        if (!isOptimized) {
            alert("请先优化命令！");
            return;
        }

        const command = document.getElementById("commandOutput").textContent;
        const response = await fetch("/save_to_mysql", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
                command: command,
                session_id: sessionID
            })
        });

        const data = await response.json();
        alert(data.message || "保存失败！");
    }
</script>
</body>
</html>